<?php
  require_once("../includes/config.php"); 
  $length = 20;
  if( isset($_POST['page'])  && !empty($_POST['page'] ))
  {
    $page =  filter_var($_POST['page'], FILTER_SANITIZE_NUMBER_INT);
    $start = $page*20 - 20;
  }
  else
  {
    $start = 0;
    $page = 1;
  }
  
  if(isset($_POST['month']))
  {
    $month = $_POST['month'];
    $year = $_POST['year'];
  }
  else
  {
    $month = date('m', time());
    $year = date('Y', time());
  }
  
  
  $sql="SELECT * FROM apartments
		WHERE apartments.owner_id=?";
		
  $sqlCount= "SELECT COUNT(*) FROM apartments
		WHERE apartments.owner_id=?";
      
  $binds = array();
  $binds['owner_id'] = $_SESSION['user_id'];
	
  if(!empty($_POST['floor#']))
  {
    if(!empty($binds))
      $and = " and ";
    else
      $and = "  ";
          
    $binds['floor#'] = $_POST['floor#'];
    $sql .= $and." floor = ?";
    $sqlCount .= $and." floor = ?";
  }
  
  if(!empty($_POST['room_name']))
  {
    if(!empty($binds))
      $and = " and ";
    else
      $and = "  ";
          
    $binds['room_name'] = $_POST['room_name'];
    $sql .= $and." apart_name = ?";
    $sqlCount .= $and." apart_name = ?";
  }
  
  $sql .= " LIMIT ?,?";
  $binds['start'] = $start;
  $binds['end'] = $length;
  $aparts = query($sql,$binds);
  
  $prices = array();
  $j = 0;
  foreach($aparts as $apart)
  {
    
    $contracts = query("SELECT * FROM contract_apartments LEFT JOIN contracts ON contracts.contract_id = contract_apartments.contract_id LEFT JOIN companies ON contracts.company_id=companies.company_id WHERE apartment_id = ? 
    and (MONTH(mildai_from) =? and year(mildai_from) =? or (MONTH(created_at) = ? and year(created_at) =?)) ORDER BY created_at", $apart['id'],$month,$year,$month,$year);
    
    foreach($contracts as $contract)
    {
      $timestamp = strtotime($contract['mildai_from']);
      $day_in = intval(date('d', $timestamp));
      
      $timestamp = strtotime($contract['miladi_out']);
      $day_out = intval(date('d', $timestamp));
      if($day_out< $day_in) //$day_out extends to other month
      {
        $max_day = cal_days_in_month ( CAL_GREGORIAN, $month, $year ); //return max number of date for a given month
        $day_out =  $max_day;
      }
      for($k = $day_in; $k <$day_out;$k++)
      {
        $price_discounted = $contract['total'] - (  ( ($contract['discount'] + $contract['co_discount']) )  ) - $contract['fixed_discount'];
        $prices[$j][$k] = round($price_discounted/$contract['period'],2);
      }
    }
    $j++;
  }
  
  $Count = query($sqlCount,$binds);
  $totalPages = $Count[0]['COUNT(*)'];
  
  render("monthly_report.php", array("title"=>"تقرير الحركة الشهرية","aparts"=>$aparts,"page"=>$page,"totalPages"=>$totalPages,"start"=>$start,"length"=>$length,"binds"=>$binds,"month"=>$month,"year"=>$year,'binds'=>$binds,"prices"=>$prices));
  
  ?>